Before we begin, take about 10 minutes or so to complete this Concepts Quiz - this is to check your understanding of some of the concepts that we have discussed so far.
This will not be graded and your answers will be anonymous so just try your best! The results will help us tackle the areas of improvements during this review session.
With the review of the concepts above, we can dive into this activity that allows us to put those concepts to practice.
| Before we clone the Github repository for the activity below, we will fork it to have our own copy. |
Start by cloning this repository.
You are a developer working for a pet adoption agency. The team has built a Paw-some website, but now your pesky Product Manager has tasked you with adding the voting functionality for the upcoming "Pet of the Month".
Let's navigate to the index.html file and open it up in our browser.
We can see the initial setup of the activity here: You should expect to see three pets on the page.
There are a few different methods we can use to accomplish the tasks on our To-Do list. For example: we could add the button for each pet using the button HTML element and then use JavaScript to add functionality to the voting system.
But for this activity we should plan to take an approach strictly utilizing JavaScript and practicing what we have learned about DOM manipulation.
Remember, DOM Manipulation isn't just for targetting elements and adding event listeners! We can also generate DOM elements! For that reason, to add "Vote" buttons to each pet on the page that count and store the votes, let's navigate to the script.js file.
Since each pet has a common class and a distinct id, we can use querySelector to gain access and manipulate the elements within those divs.
To add "Vote" buttons to each pet on the page:
Start by utilizing the document's querySelector method to gain access to the the pets.
If we save and console.log(animals), we'll see that it returns an indexed list with a length of 3 - where the 0 position is the dog, 1 is the cat, and 2 is the fish.
Cool! Now we know that our javaScript code is aware of our HTML document and its contents. With that in mind, let's go ahead and generate a button, and format the text content that will be displayed inside of it.
The element .append() function will let us attach this fresh button that just created onto the div for the dog - you can save and refresh the page to see it there!
| We know that the "dog" div is represented inside of our "animals" array at the index "0". Once we have targeted that div, we just passed the button we generated to the .append() function! |
Follow the same steps for the cat and fish.
The first task is finished. Good job!
Now that we have buttons for each pet, let's add some behaviors to those buttons. Specifically, we want add functionality so that the voting score is iterated by one when we click the button.
How can we do that?
The DOM allows us to add interactive functionality to our HTML page; it brings our page to life.
Event listeners such as click events, mouseover, and submit can be powerful ways to use the DOM.
Since we're attempting to increment the votes each time we click on a button, we want to add an event listener that listens for a click event from that button.
The voting table section has distinct ids for each pet's voting total. We can use querySelector and target element ids to gain access to the number of votes for each individual pet.
Let's isolate the vote count for the dog first and add an event listener to the button we created earlier that increments the vote by 1 for each click.
In the example above, the dogVotesCell variable has selected the element that counts the dog's vote count.
Remember that the event listener will be attached to the dogVoteBtn that we created earlier and will take in 2 arguments:
| This function is called the event handler. |
You will notice that the event handler has an argument of 'e'. The 'e' stands for event and all it's doing is offering us functionality when the event occurs. Don't worry about it too much for now as we will practice it in detail in the future.
Inside the event handler, we're instructing the listener to do a few things:
This process is repeated each time you click the dog button - the event listener is waiting for the click and you have given it instructions (the event handler function) on what to do once that happens. Save and refresh the page - your dog button should increment the vote count by 1 each time you click it.
Take some time and execute the same function for the remainder of the pets.
Almost done! Let's take care of the last task on our to-do list:
When you refresh your page, what happens to the count of votes for each pet. Do they stay? Or are they reverting back to 0?
Right, they're currently resetting every time the page is refreshed!
To store the votes between page visits, we'll utilize the global property called localStorage. We already have many of the pieces we need to implement this.
| localStorage has a few functions that perform particular tasks in finding, setting, and removing data. It can be useful when you're developing a page that needs data to persist between site visits! |
We can use the .setItem() function of localStorage in our click event to send the count of each individual pet's votes over to localStorage.
This can sound really complex! But it's only a few lines of code, and can be accomplished like so:
| Unlike our buttons, the localStorage object is a global variable that is always accessible through javaScript. We don't have to declare anything in order to gain access to it! |
Like addEventListener(), the function we are using on localStorage, setItem(), takes in 2 arguments:
the first is a string key that you name and the second is the data being stored in localStorage. You will extract that data with the key that you named in the setItem() function.
localStorage can be thought of like a locksafe - you put something inside and you create a passcode. To take the item out later, you use that passcode.
To gain access to the votes through localStorage, we'll use the getItem() function using that variable name, or "key", that we stored in the click event.
As mentioned above, we can pass the string key argument to our localStorage.getItem() function. We set it to a variable dogVotes to add the data storage functionality to the vote count.
| The above code simply checks if dogVotes exists inside of localStorage at all. If it does, then it will write the value of that content to the dogVotesCell! If it does not, no action is taken. |
It's good practice to take care of this logic at the very top of our javaScript code. This way, we know the first thing our page will do when it is loaded is check localStorage to see if there are any dogVotes!
You just have to give the same treatment to the remainder of the pets and you're done.
| Tip: implement .setItem() BEFORE .getItem() so that your code doesn't break looking for a variable that does not yet exist! |
Save and refresh your page and add votes for each pet. Now refresh again and witness the glory of the votes still being there.
Normally, we would need to manually link the JavaScript file but that is already done for us in the bottom of the index.html page, inside of the script tag.
Finally, when we finish, be sure to git add, git commit (don't forget a message!) and git push our forked repository over to github.
Check out the solutions branch for a detailed look into this activity as well the bonus tasks below!